package com.example.accessibilityhelper

import android.accessibilityservice.AccessibilityService
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityEvent.*
import android.view.accessibility.AccessibilityNodeInfo
import androidx.annotation.RequiresApi
import com.example.accessibilityhelper.WeChatHelperService.Ids.SEARCH_ADD_FRIEND_EDIT_TEXT_ID
import com.example.accessibilityhelper.WeChatHelperService.PAGE.CUSTOM_DIALOG
import com.example.accessibilityhelper.WeChatHelperService.PAGE.CUSTOM_SERVICE_CREATE_PERSONAL_SEND_MSG_PAGE
import com.example.accessibilityhelper.WeChatHelperService.PAGE.CUSTOM_SERVICE_PAGE
import com.example.accessibilityhelper.WeChatHelperService.PAGE.CUSTOM_SERVICE_SELECT_PAGE
import com.example.accessibilityhelper.WeChatHelperService.PAGE.MAIN_PAGE
import com.example.accessibilityhelper.addfriend.AddFriendFromMainPageTask
import com.example.accessibilityhelper.common.backtomain.BackToMainPageTask
import com.example.accessibilityhelper.fetchcoporation.FetchAccountCorporationInfoTask
import com.example.accessibilityhelper.group.GroupSendTask
import com.example.accessibilityhelper.util.*

class WeChatHelperService : AccessibilityService() {
    val TAG = "WeChatHelperService"
    val handler = Handler(Looper.getMainLooper())
    var taskState = 0
    var contactSelected = false

    object TimeOut {
        const val SHORT_TIME_DELAY = 200L
        const val MEDIUM_TIME_DELAY = 350L
        const val LONG_TIME_DELAY = 500L
    }

    object PAGE {
        val MAIN_PAGE = "com.tencent.wework.launch.WwMainActivity"
        val CUSTOM_SERVICE_PAGE =
            "com.tencent.wework.customerservice.controller.CustomerServiceMainActivity"
        val CUSTOM_SERVICE_CREATE_PERSONAL_SEND_MSG_PAGE = "com.tencent.wework.customerservice.controller.CustomerServiceCreatePersonalGroupSendMsgActivity"
        val CUSTOM_SERVICE_SELECT_PAGE = "com.tencent.wework.customerservice.controller.MyEnterpriseCustomerSelectListActivity"
        val CUSTOM_DIALOG  = "com.tencent.wework.common.views.dialog.CustomDialog"
        val SEARCH_ADD_FRIEND_PAGE =
            "com.tencent.wework.friends.controller.FriendAddMenu3rdActivity"
        val SEARCH_FRIEND_PAGE =
            "com.tencent.wework.friends.controller.WechatFriendAddSearchActivity"

        val CHAT_INFO_PAGE = "com.tencent.wework.contact.controller.WechatContactInfoActivity"

        val ADD_FRIEND_REQUEST_PAGE =
            "com.tencent.wework.friends.controller.WechatContactSendVerifyActivity"
    }

    init {
//        val dispatcher = Dispatcher()
//        dispatcher.offerAndPromote(AddFriendFromMainPageTask())
    }

    object Ids {
        const val MAIN_CHOICE_BUTTON_ID = "com.tencent.wework:id/h8g"
        const val MAIN_ADD_DROP_DOWN_MENU_ID = "com.tencent.wework:id/byl"

        const val SEARCH_FRIEND_EDIT_TEXT_ID = "com.tencent.wework:id/g1n"
        const val SEARCH_ADD_FRIEND_EDIT_TEXT_ID = "com.tencent.wework:id/g24"
        const val MAIN_CHOICE_ADD_BUTTON_ID = "com.tencent.wework:id/dy5"
    }

    object MMPages {
        const val MAIN_PAGE = "com.tencent.mm.ui.LauncherUI"
    }

    object MMIds {
    }

    override fun onInterrupt() {
        ToastUtil.toast("service interrupted")

    }

    override fun onCreate() {
        super.onCreate()
        ToastUtil.init(this)
        App.service = this
        ToastUtil.toast("service created")
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        ToastUtil.toast("service connected")
        Dispatcher.offerAndPromote(FetchAccountCorporationInfoTask())
        Dispatcher.offerAndPromote(BackToMainPageTask())
        Dispatcher.offerAndPromote(GroupSendTask())
    }


    @RequiresApi(Build.VERSION_CODES.N)
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        Log.i(
            TAG,
            "onAccessibilityEvent: ${SymbolicUtil.getSymbolicTypeName(event!!.eventType)} -- ${event.className}"
        )
        App.onAccessibilityEvent(this,event)
        Dispatcher.dispatch(this,event)
//        event.eventType.apply {
//            when (this) {
//                TYPE_WINDOW_STATE_CHANGED -> {
//                    when (event.className) {
//                        MAIN_PAGE -> switchToWorkTab()
//                        CUSTOM_SERVICE_PAGE -> clickGroupMessageSenderHelper()
//                        CUSTOM_SERVICE_CREATE_PERSONAL_SEND_MSG_PAGE -> {
//                            if(contactSelected.not()) {
//                                chooseContactForGroupMsgSender()
//                            }else{
//                                fillSendMsg()
//                            }
//                        }
//                        CUSTOM_SERVICE_SELECT_PAGE -> chooseSingleContact()
//                        CUSTOM_DIALOG -> confirmSend()
//                    }
//                }
//
//                TYPE_WINDOW_CONTENT_CHANGED -> {
//                    val recyclerViewNode =
//                        rootInActiveWindow?.findAccessibilityNodeByShortViewId("s8")
//                    if (event.className == "androidx.recyclerview.widget.RecyclerView" && recyclerViewNode?.isNotEmpty()  == true) {
//                        recyclerViewNode.firstOrNull()?.getChild(1)?.click()
//                    }
//                }
//            }
//        }
//        event.apply {
//            val root = rootInActiveWindow
//            when (eventType) {
//                TYPE_WINDOW_STATE_CHANGED -> {
//                    when (className) {
//                        MAIN_PAGE -> if (taskState == 0) openChoiceDropdownMenu()
//                        SEARCH_ADD_FRIEND_PAGE -> {
//                            requestFocus()
//                        }
//                        SEARCH_FRIEND_PAGE -> {
//                            fillWeChatId("13247185523")
//                        }
//
//                        CHAT_INFO_PAGE ->{
//                            clickAddFriendButton()
//                        }
//
//                        ADD_FRIEND_REQUEST_PAGE -> clickAndSendInviteRequest()
//
//                    }
//
//                }
//
//                TYPE_VIEW_TEXT_SELECTION_CHANGED -> {
//                    if (taskState == 3)
//                        clickSearchItem()
//                }
//            }
//        }
    }

    private fun confirmSend() {
        rootInActiveWindow.findAccessibilityNodeByShortViewId("bei").firstOrNull()?.click()
    }

    private fun fillSendMsg() {
        rootInActiveWindow
            .findAccessibilityNodeByShortViewId("b6s")
            .firstOrNull()
            ?.fill("hello,this msg is from wework accessibility service")
        rootInActiveWindow.findAccessibilityNodeByShortViewId("b33").firstOrNull()?.click()
    }

    private fun chooseSingleContact() {
        rootInActiveWindow
            .findAccessibilityNodeByShortViewId("c9d")
            .firstOrNull()?.getChild(3)
            ?.findAccessibilityNodeByShortViewId("dyi")
            ?.firstOrNull()
            ?.gestureClick(this)
        rootInActiveWindow.findAccessibilityNodeByShortViewId("g43").firstOrNull()?.click()
        contactSelected = true

    }

    private fun chooseContactForGroupMsgSender() {
        rootInActiveWindow.findAccessibilityNodeByShortViewId("g4d").firstOrNull()?.gestureClick(this)
//        rootInActiveWindow.findAccessibilityNodeByShortViewId("dcn").firstOrNull()?.click()
    }

    private fun clickGroupMessageSenderHelper() {
        val root = rootInActiveWindow
        root.findAccessibilityNodeByShortViewId("bhm").firstOrNull()?.getChild(1)?.click()
    }

    private fun switchToWorkTab() {
        val root = rootInActiveWindow
        root.findAccessibilityNodeByShortViewId("gsj").firstOrNull()?.getChild(2)?.click()
    }

    private fun clickAndSendInviteRequest() {
        rootInActiveWindow.findAccessibilityNodeByShortViewId("cnv").firstOrNull()?.apply {
            click()
        }
    }

    private fun clickAddFriendButton() {
        val root = rootInActiveWindow
        root.findAccessibilityNodeByShortViewId("gt").firstOrNull()?.apply {
            click()
        }
    }

    private fun clickSearchItem() {
        val root = rootInActiveWindow
        val first = root.findAccessibilityNodeByShortViewId("he1").first()
        first.apply {
            AccessibilityUtils.clickByGesture(this@WeChatHelperService, this)
        }
    }

    private fun fillWeChatId(id: String) {
        val root = rootInActiveWindow
        val searchEditTextNode =
            root.findAccessibilityNodeInfosByViewId(Ids.SEARCH_FRIEND_EDIT_TEXT_ID).first()
        searchEditTextNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply {
            putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, id)
        })
        taskState = 3
    }

    @RequiresApi(Build.VERSION_CODES.N)
    private fun requestFocus() {
        handler.postDelayed({
            val root = rootInActiveWindow
            val editTextNode =
                root.findAccessibilityNodeInfosByViewId(SEARCH_ADD_FRIEND_EDIT_TEXT_ID).first()
            AccessibilityUtils.clickByGesture(this, editTextNode)
            taskState = 2
        }, 1000L)
    }


    private fun openChoiceDropdownMenu() {
        val root = rootInActiveWindow
        val buttonNode =
            root.findAccessibilityNodeInfosByViewId(Ids.MAIN_CHOICE_BUTTON_ID).firstOrNull()
        buttonNode?.apply {
            performAction(AccessibilityNodeInfo.ACTION_CLICK)
            handler.postDelayed({
                val newRoot = rootInActiveWindow
                val addFriendDropdownMenu =
                    newRoot.findAccessibilityNodeInfosByViewId(Ids.MAIN_ADD_DROP_DOWN_MENU_ID)
                        .first()
                val addFriendMenuItem = addFriendDropdownMenu.getChild(1)
                addFriendMenuItem.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            }, TimeOut.MEDIUM_TIME_DELAY)
        }

    }


}